// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import { LQCollide } from "../../lq_collide_system/lq_collide";
import UITools from "../common/utils/UITools";
import Utils from "../common/utils/Utils";
import { $, cNodePool, cSound, cUI, gameData } from "../config/Config";
import { skill_data_text } from "../dataUtils/DataClass";
import ShowBoss from "../items/pars/ShowBoss";
import SkillCtrl from "../items/skills/SkillCtrl";
import { p_data_mager } from "../Mangers/playerDataMager/PlayerDataMager";
import { gameScene } from "../view/scene/GameScene";

const { ccclass, property } = cc._decorator;

@ccclass
export default class PlayerCtrl extends LQCollide {
    @property(cc.Node)
    gunNode: cc.Node = undefined;
    @property(cc.Node)
    body: cc.Node = undefined;
    @property(SkillCtrl)
    skill_ctrl: SkillCtrl = undefined;

    _ctrl_shoot: boolean = false;

    shootTimer: number = -1;
    shootTimeFlag: number = 0;

    /**血量 */
    _HP: number = 10;
    _MaxHP: number = 10;
    /**移动速度 */
    _speed: number = 2.5;
    /**射击冷却 */
    _bullet_cd: number = 350;
    /**弹道速度 */
    _bullet_speed: number = 0.5;
    /**穿透数 */
    _penetrate_count: number = 0;
    /**体积 百分比*/
    _volume: number = 1;
    /**射程 */
    _shoot_range: number = 400;
    /**发射器数量 */
    _shoot_count: number = 1;
    /**弹道体积 */
    _bullet_volume: number = 1;
    /**生命偷取 */
    _life_stealing: number = 0;
    /**冰冻属性 */
    _frozen: number = 0;
    /**幸运 */
    _lucky: number = 0.2;

    /**受伤无敌状态cd */
    _hurt_cd: boolean = false;
    /**单局游戏复活次数 */
    _revivel_count: number = 0;
    // LIFE-CYCLE CALLBACKS:

    // onLoad () {}

    start() {
        this.initData();
        if (gameData._auto_shoot) this.startShoot();
    }

    initData() {
        this._revivel_count = 0;
        for (let i = 0; i < p_data_mager.attArr.length; i++) {
            this[p_data_mager.attArr[i]] = p_data_mager.getAddAttValue(i);
            console.log("------------key:" + p_data_mager.attArr[i] + "  value:" + this[p_data_mager.attArr[i]]);
        }
        this._MaxHP = this._HP;
        if (gameData._is_strong_start) {
            this._shoot_count++;
        }
        this.updateHpView();
    }

    getPos() {
        return this.node.position;
    }

    /**
     * 通过向量改变枪的角度指向
     * @param angle 
     */
    changeGunDir(angle: number) {
        // console.log('--------------angle:', angle);
        // this.gunNode.angle = angle;
        this.node.angle = angle;
    }

    //开始射击
    startShoot() {
        // this.shootTimeFlag = 0;qwaw
        if (this.shootTimer == -1) this.shootTimer = setInterval(this.shootTimeFun.bind(this), 50);
    }

    //停止射击
    stopShoot() {
        if (!gameData._auto_shoot) {
            clearInterval(this.shootTimer);
            this.shootTimer = -1;
        }
    }

    onDestroy() {
        clearInterval(this.shootTimer);
    }

    setAngle(dir: cc.Vec2) {
        if (this.shootTimer == -1) {
            this.node.angle = Utils.vector_to_angle(dir);
        }
    }

    shootTimeFun() {
        if (gameScene.is_pause) return;
        if (gameScene.EnemyRoot.node.childrenCount == 0) {
            if (!gameScene.heroCtrl._ctrl_shoot && gameData._auto_shoot) return;
        }
        this.shootTimeFlag += 50;
        if (this.shootTimeFlag % this._bullet_cd < 50) {
            cSound.playEffect($.Sound.shoot0);
            for (let i = 0; i < this._shoot_count; i++) {
                let angle;
                if (this._ctrl_shoot) {
                    angle = this.node.angle;
                } else {
                    let pos = gameScene.EnemyRoot.getCloserEnemyPos(this.node.position);
                    if (pos) {
                        angle = Utils.getAngle(this.node.position, pos);
                        // this.node.angle = angle;
                        this.changeAngleAction(angle);
                    } else {
                        angle = this.node.angle;
                    }
                }
                if (this._shoot_count == 1) {
                } else if (this._shoot_count % 2 == 0) {
                    if (i % 2 == 0) {
                        angle += 15 * (i / 2);
                    } else {
                        angle += -15 * Math.floor(i / 2) - 15;
                    }
                } else {
                    if (i % 2 == 0) {
                        angle += 15 * (i / 2);
                    } else {
                        angle += -15 * Math.ceil(i / 2);
                    }
                }
                let dir = Utils.angle_to_vector(angle);//角度转换为向量
                gameScene.shootBullet(dir, this.node.position)
            }
            this.gunAction();
        }
    }

    changeAngleAction(angle: number) {
        cc.tween(this.node)
            .to(0.1, { angle: angle })
            .start();
    }

    gunAction() {
        this.gunNode.stopAllActions();
        this.gunNode.x = 25 * this.node.scale;
        cc.tween(this.gunNode)
            .by(0.05, { x: -15 })
            .by(0.05, { x: 15 })
            .start();
    }

    // @ts-ignore
    public on_collide(collide: LQCollide): void {
    }

    //@ts-ignore
    public on_enter(collide: LQCollide) {
        if (collide.collide_category == 8) {
            if (collide.node.getChildByName("dianciflag")) return;
            this.by_hurt(collide);
        } else if (collide.collide_category == 16) {
            this.by_hurt(collide);
            gameScene.addEnemyShootBoom(collide.node.position);
        }
    }

    //@ts-ignore
    public on_exit(collide: LQCollide) {
    }

    by_hurt(collide: LQCollide) {
        if (this._hurt_cd) return;
        if (gameScene.is_pause) return;
        // UITools._hurtColor(this.gunNode);
        if (this._HP == 0) return;
        UITools._hurtColor(this.body);
        this._HP -= collide._hurt;
        if (this._HP <= 0) {
            this._HP = 0;
            console.log('-----------游戏结束');
            gameScene.is_pause = true;
            this.deathAction();

        }
        this.updateHpView();
    }

    changeHurdCd(time: number = 500) {
        this._hurt_cd = true;
        setTimeout(() => {
            this._hurt_cd = false;
        }, time);
    }

    /**回复生命 */
    addBlood(value: number) {
        this._HP += value;
        if (this._HP > this._MaxHP) this._HP = this._MaxHP;
        this.updateHpView();
    }

    updateHpView() {
        let value = this._HP / this._MaxHP;
        gameScene.GameUI.hpPro.progress = value;
        gameScene.GameUI.hpLabel.string = (value*100)/100*100 + "%";
    }

    deathAction() {
        cc.tween(this.node)
            .to(1, { opacity: 0 })
            .call(() => {
                if(this._revivel_count == 0){
                    gameScene.gameRevival();
                }else{
                    gameScene.gameResult();
                }
            })
            .start();
    }

    rerivalAction(){
        cNodePool.get($.Prefab.showBoss).then(value => {
            value.parent = this.node.parent;
            value.getComponent(ShowBoss).initState(this._key, this.node.position);
        })
        cc.tween(this.node)
        .to(1, { opacity: 255 })
        .call(() => {
            gameScene.resumeGame();
            this.changeHurdCd(2000);
        })
        .start();
        this._revivel_count++;
        this._HP = this._MaxHP;
        this.updateHpView();
    }

    changeData(data: skill_data_text) {
        if (data.sub_key != "") {//有衰减项
            if (data.sub_percent) {
                this[data.sub_key] += (data.sub_value * this[data.sub_key]);
                this[data.sub_key] = Math.floor((this[data.sub_key] * 100)) / 100;
            } else {
                this[data.sub_key] += data.sub_value;
            }
            console.log('------------衰减:', data.sub_key, " 衰减数值:", data.sub_value, " 衰减后的数据：", this[data.sub_key]);
        }

        if (data.add_percent) {
            this[data.add_key] += (data.add_value * this[data.add_key]);
            this[data.add_key] = Math.floor((this[data.add_key] * 100)) / 100;
        } else {
            this[data.add_key] += data.add_value;
        }
        console.log('------------增幅:', data.add_key, " 增幅数值:", data.add_value, " 增加后的数据：", this[data.add_key]);
        if (data.add_key == "_MaxHP") this._HP += data.add_value;
        if (this._HP > this._MaxHP) this._HP = this._MaxHP;
        if (this._bullet_cd < 50) this._bullet_cd = 50;
        this.updateHpView();
        this.updateVolume();
    }

    updateSkill(key: string) {
        this.skill_ctrl.updateSkillTimerById(key);
    }

    updateVolume() {
        this.node.scale = this._volume;
        // this.node.width = 60 * this._volume;
        // this.node.height = 60 * this._volume;
        this.radius = 30 * this._volume;
    }

    // update (dt) {}
}
